using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using Hotran.Audio;

public class Game : MonoBehaviour
{
    //[SerializeField] KeyEvent input;
    //[SerializeField] PackSpawner packSpawner;

    [SerializeField] AudioClip gameOverSound;

    [Header("Speed")]
    [SerializeField] private float startSpeed = 3f;
    [SerializeField] private float addSpeedTime = 3f;
    [SerializeField] private float addSpeed = 0.1f;
    [SerializeField] private float maxSpeed = 10f;
    private float addSpeedTimer;
    
    /// <summary>
    /// ���ʹ��ٶ�
    /// </summary>
    public static float Speed { get; private set; }

    /// <summary>
    /// ��Դ��ʹ���ʼ�ٶ������˶���
    /// </summary>
    public float AddedSpeed => Speed - startSpeed;

    /// <summary>
    /// �Ƿ񿴹��̳�
    /// </summary>
    public static bool TipShowed { get; set; } = false;

    public bool Started { get; private set; } = false;
    public bool Paused { get; private set; } = false;

    private int health = 3;
    /// <summary>
    /// ����ֵ
    /// </summary>
    public int Health 
    { 
        get => health; 
        set
        {
            if (health != value)
            {
                health = value;
                HealthChanged?.Invoke();
                if (health <= 0)
                    GameOver();
            }
            else health = value;
        }
    }

    /// <summary>
    /// ����
    /// </summary>
    public int Score { get; set; } = 0;

    public event UnityAction HealthChanged;
    public event UnityAction GameStarted;
    public event UnityAction GameEnded;

    private void Update()
    {
        if (!Started) return;
        if (addSpeedTimer >= 0f)
        {
            addSpeedTimer -= Time.deltaTime;
            if (addSpeedTimer <= 0f)
            {
                if (Speed <= maxSpeed)
                    Speed += addSpeed;
                addSpeedTimer = addSpeedTime;
            }
        }
    }

    public void StartGame()
    {
        Started = true;

        Speed = startSpeed;
        
        GameStarted?.Invoke();
    }

    /// <summary>
    /// ���¶�ȡ����
    /// </summary>
    public void Restart()
    {
        Debug.Log($"Killed {DOTween.KillAll()} tweens");

        Time.timeScale = 1f;
        SceneManager.LoadScene(gameObject.scene.buildIndex);
    }

    public void ReturnToMenu()
    {
        SceneManager.LoadScene(0);
    }

    /// <summary>
    /// �л���ͣ/����
    /// </summary>
    public void TogglePause()
    {
        Paused = !Paused;
        Time.timeScale = Paused ? 0f : 1f;
    }

    private void GameOver()
    {
        AudioPlayer.Instance.PlaySound(gameOverSound);
        AudioPlayer.Instance.Disable();

        Started = false;

        GameEnded?.Invoke();
    }

}
